<template>
  <div class="app-container">
    <van-form @submit="handleQuery"  ref="formRef">
      <van-cell-group>
        <van-field
          v-model="queryParams.yuceGupiaoDaima"
          label-width="68px"
          name="yuceGupiaoDaima"
          is-link
          readonly
          clickable
          @click="showStockPicker = true"
          :value="queryParams.yuceGupiaoDaima"
        />
        <van-popup v-model:show="showStockPicker" position="bottom" round>
          <van-picker
            show-toolbar
            :columns="gupiaoOptions"
            @confirm="onStockConfirm"
            @cancel="showStockPicker = false"
            title="选择股票"
          />
        </van-popup>
        <van-field
          name="startTime"
          label-width="68px"
        >
          <template #input>
            <van-radio-group v-model="queryParams.startTime" direction="horizontal" @change="handleYearRangeChange">
              <van-radio 
                v-for="item in queryParams.yearRangeOptions"
                :key="item.value"
                :name="item.value"
              >
                {{ item.label }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="dateRangeText"
          label-width="68px"
          name="dateRange"
          is-link
          readonly
          clickable
          @click="handleShowDatePicker"
        />
      <van-popup v-model:show="showDatePicker" position="bottom" round>
        <van-date-picker
          v-model="tempDateRange"
          type="year"
          title="选择年份"
          @confirm="onYearRangeConfirm"
          @cancel="onYearRangeCancel"
          :columns-type="['year', 'year']"
          :min-date="minDate"
          :max-date="maxDate"
        />
      </van-popup>
      </van-cell-group>
      <div style="margin: 12px 16px; display: flex; gap: 6px;">
        <van-button 
          round 
          size="small"
          type="primary" 
          native-type="submit"
          style="flex: 1; height: 36px; font-size: 14px;"
        >
          查询
        </van-button>
        <van-button 
          round 
          size="small"
          style="flex: 1; height: 36px; font-size: 14px; margin-top: 0;"
          @click="resetQuery"
        >
          重置
        </van-button>
      </div>
    </van-form>
    <div ref="chartContainer" class="chart-container"></div>
    <div class="market-analysis">
      <p>内容解读</p>
      <pre class="content-pre">{{ contentData }}</pre>
    </div>
  </div>
</template>
<script setup>
import * as echarts from 'echarts';
import { showToast } from 'vant'
import { useElementSize } from '@vueuse/core'
import { getGupiaoList, getStatistics, getAnalysisContent} from "@/api/trend/yanshi";
const formRef = ref(null);
const showStockPicker = ref(false);
const tempDateRange = ref([new Date().getFullYear(),new Date().getFullYear()]);
const showDatePicker = ref(false);
const skipYearRangeChange = ref(false);
const minDate = new Date(1998, 0);
const maxDate = new Date(new Date().getFullYear(),0);
const chartContainer = ref(null);
const dateRangeText = ref('请选择日期范围');
const gupiaoOptions = computed(() => {
  return gupiaoList.value.map(item => ({
    text: item.gupiaoName,
    value: item.gupiaoName
  }));
});
const handleShowDatePicker=()=> {
  tempDateRange.value = [...queryParams.value.dateRange];
  showDatePicker.value = true;
}

const onStockConfirm = ({ selectedOptions }) => {
  if (selectedOptions && selectedOptions[0]) {
    skipYearRangeChange.value = true;
    queryParams.value.yuceGupiaoDaima = selectedOptions[0].value;
    showStockPicker.value = false;
    if(!queryParams.value.startTime) {
      queryParams.value.startTime = getYearRange('last10Years');
    }
    if(queryParams.value.dateRange && queryParams.value.dateRange.length>0) {
      initDatePicker();
    }
    handleGetStatisticsData(queryParams.value.startTime,String(currentYear));
    nextTick(() => {
      skipYearRangeChange.value = false;
    });
  }
};
const onYearRangeCancel = () => {
  showDatePicker.value = false;
};
const onYearRangeConfirm = (pickerResult) => {
  skipYearRangeChange.value = true;
  const { selectedValues } = pickerResult;
  if (!selectedValues || selectedValues.length !== 2) {
    showToast({
      type: 'fail',
      message: '请选择完整的年份范围',
      duration: 2000
    })
    return;
  }
  const startYear = Number(selectedValues[0]);
  const endYear = Number(selectedValues[1]);
  if (startYear > endYear) {
    showToast({
      type: 'fail',
      message: '开始年份不能大于结束年份',
      duration: 2000
    })
    showDatePicker.value = false;
    return;
  }
  // if (startYear == endYear) {
  //   showToast({
  //     type: 'fail',
  //     message: '开始年份不能等于结束年份',
  //     duration: 2000
  //   })
  //   showDatePicker.value = false;
  //   return;
  // }
  queryParams.value.dateRange = [...selectedValues];
  //这里
  dateRangeText.value = queryParams.value.dateRange.length === 2 
    ? queryParams.value.dateRange.join('至')
    : '请选择日期范围';
  // queryParams.value.dateRange = [String(startYear), String(endYear)];
  queryParams.value.startTime = '';
  showDatePicker.value = false;
  nextTick(() => {
    skipYearRangeChange.value = false;
  });
};
let myChart = null;
// 0.1进、0.5进、一进、五进、十进、百进、五百  不算灵活  新增区间需要额外增加
const colorLibrary = ['#DEF0D2','#D7F2EF','#DAE3FD', '#EAE0F7','#FADDDC','#FCE9D1','#FEFBD0'];
// TODO: 数据待调整
const barData = [];
// const barData = [75, 78, 56, 89, 65, 92, 80,120];//无实际意义，用来生成高亮样式
// const categories = ['2015', '2016', '2017', '2018', '2019', '2020','2021'];
// const lineData1 = [45, 78, 65, 90, 85, 92,52,75, 88, 95, 110];
const lineData2 = [10, 30, 45, 30, 65, 15,110,40, 55, 70, 125];
// 高亮配置(后面改成根据数据动态生成)
// const highlightConfig = [
//   { index: 0, values: [50], colors: ['rgba(139,71,38,0.8)'] },
//   { index: 1, values: [50], colors: ['rgba(139,71,38,0.8)'] },
//   { index: 2, values: [50], colors: ['rgba(139,71,38,0.8)'] },
//   { index: 3, values: [70], colors: ['rgba(255,255,0,0.8)'] },
//   { index: 4, values: [50], colors: ['rgba(139,71,38,0.8)'] },
//   { index: 5, values: [70], colors: ['rgba(255,255,0,0.8)'] },
//   { index: 6, values: [70], colors: ['rgba(255,255,0,0.8)'] },
//   { index: 7, values: [50], colors: ['rgba(139,71,38,0.8)'] },
//   { index: 8, values: [90], colors: ['rgba(139,10,80,0.8)'] },
//   { index: 9, values: [90], colors: ['rgba(139,10,80,0.8)'] },
//   { index: 1, values: [30, 78], colors: ['#0096FF', '#FFBF00'] },
//   { index: 2, values: [45, 65], colors: ['#0BDA51', '#FFBF00'] },
//   { index: 3, values: [30, 92], colors: ['#0096FF', '#FF5F1F'] },
//   { index: 4, values: [65, 85], colors: ['#FFBF00', '#FF5F1F'] },
//   { index: 5, values: [15, 90], colors: ['blue', '#FF5F1F'] },
//   { index: 6, values: [110, 52], colors: ['#E0115F', '#0BDA51'] },
//   { index: 7, values: [40, 75], colors: ['#0BDA51', '#FFBF00'] },
//   { index: 8, values: [55, 88], colors: ['#0BDA51', '#FF5F1F'] },
//   { index: 9, values: [70, 95], colors: ['#FFBF00', '#FF5F1F'] },
// ];
const currentYear = new Date().getFullYear();
const { proxy } = getCurrentInstance();
const gupiaoList = ref([]);
const statisticsData = ref({});
const contentData = ref({});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startTime: getYearRange('last10Years'),
    // endTime: currentYear,
    yuceGupiaoDaima: '华联股份',
    yuceZhouqi: null,
    yuceDone: undefined,
    yearRangeOptions: [
        { label: '近三年', value: getYearRange('last3Years') },
        { label: '近五年', value: getYearRange('last5Years') },
        { label: '近十年', value: getYearRange('last10Years') }
    ],
    dateRange: [String(currentYear), String(currentYear)],// 实际使用的日期范围
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
function handleYearRangeChange(rangeType) {
  if (skipYearRangeChange.value) return; // 如果是日期选择触发的就跳过
  if(queryParams.value.dateRange && queryParams.value.dateRange.length > 0) {
    initDatePicker();
  }
  handleGetStatisticsData(queryParams.value.startTime,String(currentYear));
}
function getYearRange(value) {
    switch(value) {
      case 'last3Years':
        return String(currentYear - 2);
      case 'last5Years':
        return String(currentYear - 4);
      case 'last10Years':
        return String(currentYear - 9);
      default:
        return '';
    }
  }
function handleGetStatisticsData(startTime, endTime) {
  getStatistics({
    "startTime": startTime,
    "endTime": endTime,
    "guPiaoName": queryParams.value.yuceGupiaoDaima,
  }).then(response => {
    if (response.code == 200) {
      statisticsData.value = response.data
      initChart()
    } else {
      //ElMessage.error(response.msg)
    }
  })
}
function handleGetAnalysisContent() {
  getAnalysisContent().then(response => {
    if (response.code == 200) {
      contentData.value = response.data
    } else {
      //lMessage.error(response.msg)
    }
  })
}
function initDatePicker () {
  dateRangeText.value = '请选择日期范围'
  queryParams.value.dateRange = [String(currentYear), String(currentYear)];
}
function handleGetGupiaoList() {
  getGupiaoList().then(response => {
    if (response.code == 200) {
      gupiaoList.value = response.data
    } else {
      //ElMessage.error(response.msg)
    }
  })
}
function handleQuery() {
  if(queryParams.value.dateRange && queryParams.value.dateRange.length > 0 ){
    handleGetStatisticsData(queryParams.value.dateRange[0],queryParams.value.dateRange[1]);
  } else {
    handleYearRangeChange();
  }
}
async function resetQuery() {
   // 1. 设置标志位（阻止handleYearRangeChange触发）
  skipYearRangeChange.value = true;
  // 1. 重置表单数据
  queryParams.value = {
    ...queryParams.value,
    startTime: getYearRange('last10Years'), // 重置为近十年
    dateRange: [],                         // 清空日期范围
    yuceGupiaoDaima: '华联股份'            // 重置默认值
  };
  // 或
  //formRef.value.resetValidation();
  initDatePicker();
  handleGetStatisticsData(queryParams.value.startTime,String(currentYear));
  nextTick(() => {
    skipYearRangeChange.value = false;
  });
}
// 计算每个图例项的起始位置
const itemWidth = 50; // 每个图例项占用的宽度
const startLeft = 10; // 起始左侧位置
// 定义Y轴区间标签（不设置背景色）
const yAxisRanges = [
  { min: 0, max: 20, name: '0.1进' },
  { min: 20, max: 40, name: '0.5进' },
  { min: 40, max: 60, name: '一进' },
  { min: 60, max: 80, name: '五进' },
  { min: 80, max: 100, name: '十进' },
  { min: 100, max: 120, name: '百进' },
  { min: 120, max: 140, name: '五百进' }
];
function generateHighlightConfig() {
  const line1Data = statisticsData.value.formatJinzhi;
  const line2Data = [125,85,20,20,25,25,20,25,25,25];
  const allLineData = {lineData1: line1Data, lineData2: line2Data};
  const { lineData1, lineData2 } = allLineData; // 场景一和冲为平的数据
  // const allSeriesData = [lineData1, lineData2]; // 所有折线数据数组
  const allSeriesData = [lineData1]
  return lineData1.map((_, dataIndex) => {
    const pointConfig = {
      index: dataIndex,
      values: [], // 存储所有折线在该点的值
      colors: []  // 存储对应的颜色
    };
    allSeriesData.forEach((seriesData, seriesIndex) => {
      const value = seriesData[dataIndex];
      if (value == null) return;
      const mappedValue = preciseRangeMap([value])[0];
      let color;
      if (mappedValue < 20) {
        color = colorLibrary[0];
      } else if (mappedValue < 40) {
        color = colorLibrary[1];
      } else if(mappedValue<60) {
        color = colorLibrary[2];
      } else if(mappedValue<80) {
        color = colorLibrary[3];
      } else if(mappedValue<100) {
        color = colorLibrary[4];
      } else if(mappedValue<120) {
        color = colorLibrary[5];
      } else if(mappedValue<140) {
        color = colorLibrary[6];
      }
      else {
        color = '#ccc';
      }
      pointConfig.values.push(mappedValue);
      pointConfig.colors.push(color);
    });
    return pointConfig;
  });
}
// 定义图例项数据
const legendItems = [
  { name: '0.1进', color: '#DEF0D2' },
  { name: '0.5进', color: '#D7F2EF' },
  { name: '一进', color: '#DAE3FD' },
  { name: '五进', color: '#EAE0F7' },
  { name: '十进', color: '#FADDDC' },
  { name: '百进', color: '#FCE9D1' },
  { name: '五百进', color: '#FEFBD0' },
];
// 动态生成children数组
const children = legendItems.map((item, index) => [
  // 矩形元素
  {
    type: 'rect',
    left: startLeft + index * itemWidth,
    top: 3,
    shape: { width: 6, height: 6 },
    style: { fill: item.color }
  },
  // 文本元素
  {
    type: 'text',
    left: startLeft + index * itemWidth + 10,
    top: 0,
    style: {
      text: item.name,
      fill: '#333',
      fontSize: 12
    }
  }
]).flat(); // 将二维数组扁平化
// 生成高亮区域数据
function generateMarkAreaData() {
  const highlightConfig = generateHighlightConfig();
  return highlightConfig.flatMap(config => 
    config.values.map((value, i) => [
      {
        xAxis: config.index,
        yAxis: Math.floor(value / 20) * 20,
        min: 0,
        max: 140,  // 必须大于等于五百进的最大值(140)
        interval: 20,  // 与区间划分保持一致
        itemStyle: {
          color: config.colors[i],
          borderColor: config.colors[i].replace('0.3', '0.6'),
        }
      },
      {
        xAxis: config.index,
        yAxis: Math.floor(value / 20) * 20 + 20
      }
    ])
  );
}
const keyValueMap = {
  // 0.1进区间 (0-20)
  0.1: 4,      // 接近底部
  0.25: 10,    // 中部偏下
  0.5: 20,     // 区间顶部
  
  // 0.5进区间 (20-40)
  0.75: 25,    // 中部偏下
  1: 40,       // 区间顶部
  
  // 一进区间 (40-60)
  2.5: 50,     // 正中间
  5: 60,       // 区间底部(修正点)
  
  // 五进区间 (60-80)
  7.5: 70,     // 正中间
  10: 80,      // 区间顶部
  
  // 十进区间 (80-100)
  25: 90,      // 正中间
  50: 100,     // 区间顶部
  
  // 百进区间 (100-120)
  75: 110,     // 正中间
  100: 120,    // 区间顶部
  
  // 五百进区间 (120-140)
  250: 130,    // 正中间
  500: 140     // 区间顶部
};
function preciseRangeMap(originalData) {
  return originalData.map(value => {
    // 精确匹配
    if (keyValueMap[value] !== undefined) {
      return keyValueMap[value];
    }
    
    // 线性映射（针对非关键值）
    if (value >= 0 && value < 0.5) return mapLinear(value, 0, 0.5, 0, 20);
    if (value >= 0.5 && value < 1) return mapLinear(value, 0.5, 1, 20, 40);
    if (value >= 1 && value < 5) return mapLinear(value, 1, 5, 40, 60);
    if (value >= 5 && value < 10) return mapLinear(value, 5, 10, 60, 80);
    if (value >= 10 && value < 50) return mapLinear(value, 10, 50, 80, 100);
    if (value >= 50 && value < 100) return mapLinear(value, 50, 100, 100, 120);
    if (value >= 100 && value <= 500) return mapLinear(value, 100, 500, 120, 140);
    
    return 0; // 默认值
  });
}

// 线性映射辅助函数
function mapLinear(value, inMin, inMax, outMin, outMax) {
  return outMin + (outMax - outMin) * ((value - inMin) / (inMax - inMin));
}
function getRangeName(value) {
  const rangeRules = [
    { min: 0, max: 0.5, name: '0.1-0.4元' },
    { min: 0.5, max: 1, name: '0.5-0.9元' },
    { min: 1, max: 5, name: '1-4元' },
    { min: 5, max: 10, name: '5-9元' },
    { min: 10, max: 50, name: '10-40元' },
    { min: 50, max: 100, name: '100-400元' },
    { min: 100, max: 500, name: '500-900元' }
  ];
  
  const rule = rangeRules.find(r => value >= r.min && value < r.max);
  return rule ? rule.name : '未知价格';
}
function generateYears(startYear, endYear) {
    let years = [];
    for (let year = startYear; year <= endYear; year++) {
        years.push(String(year));
    }
    return years;
}
// 初始化图表
function initChart() {
  if (!chartContainer.value) return;
  myChart = echarts.init(chartContainer.value);
  const line1Data = statisticsData.value.formatJinzhi || [];
  // 防止没有返回年份信息时候，X轴会没有年份轴
  let XYears = [];
  if(queryParams.value.startTime) {
    XYears = generateYears(queryParams.value.startTime, currentYear)
  } else if(queryParams.value.dateRange && queryParams.value.dateRange.length > 0) {
    XYears = generateYears(queryParams.value.dateRange[0], queryParams.value.dateRange[1])
  }
  const categories = statisticsData.value.years || XYears;
  // 目前不清楚多条数据时数据结构，后续需要调整动态生成配置
  const mappedLine1Data = preciseRangeMap(line1Data);
  const mappedLine2Data = preciseRangeMap([125,85,20,20,25,25,20,25,25,25]);
   // 准备包含原始值的数据
  const seriesData = line1Data.map((value, index) => ({
    value: mappedLine1Data[index],
    originalValue: value,
    name: statisticsData.value.years?.[index] || `${index}`
  }));
  const seriesData2 = [125,85,20,20,25,25,20,25,25,25].map((value, index) => ({
    value: mappedLine2Data[index],
    originalValue: value,
    name: statisticsData.value.years?.[index] || `${index}`
  }));
  const dynamicSeries = [
    //没有实际意义，为了生成高亮区域
    {
        name: '',
        type: 'pictorialBar',
        symbol: 'rect',
        showSymbol: false,  // 不显示标记点
        label: { show: false },  // 不显示标签
        tooltip: { show: false },  // 不显示提示
        symbolSize: [30, 10],
        symbolMargin: 5,
        symbolRepeat: 'fixed', // 改为fixed确保均匀分布
        symbolRepeat: true,
        symbolBoundingData: 100,
        data: barData,
        itemStyle: {
          color: 'rgba(240, 240, 240,0)',
          //color: { image: patternImg, repeat: 'repeat' },
          opacity: 1,
          borderColor: '#ccc',
          borderWidth: 0.5
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
            borderColor: '#999',
            borderWidth: 1
          }
        },
        markArea: {
          silent: true,
          itemStyle: {
            borderWidth: 0.5,
            borderType: 'solid'
          },
          data: [
            ...generateMarkAreaData(),
            ...yAxisRanges.map(range => {
              const middleY = (range.min + range.max) / 2;
              return [{
                yAxis: range.min,
                // itemStyle: {
                //   color: range.color
                // },
                label: {
                  show: false,
                  position: 'left',
                  formatter: range.name,
                  color: '#333',
                  fontSize: 10,
                  distance: 10, // 调整标签与Y轴的距离
                  verticalAlign: 'middle',
                  padding: [0, 5],
                  // 计算标签在区间中间的位置
                  y: middleY - range.min - 10
                }
              }, {
                yAxis: range.max
              }];
            })
          ]
        },
        z: 10
      },
      {
        name: '场景一',
        type: 'line',
        data: seriesData,
        symbol: 'circle',
        symbolSize: 10,
        itemStyle: { color: '#FF4040' },
        lineStyle: { width: 2, type: 'solid', color: '#FF4040' },
        z: 15
      },
      // {
      //   name: '冲为平',
      //   type: 'line',
      //   data: seriesData2,
      //   symbol: 'circle',
      //   symbolSize: 8,
      //   itemStyle: { color: '#b9a1dd' },
      //   lineStyle: { width: 2, type: 'solid', color: '#b9a1dd' },
      //   z: 15
      // }
  ];
  const option = {
    graphic: [{
      type: 'group',
      right: 0,
      top: '30',
      children: children
    }],
    title: {
      text: '趋势图示',
      top: 10,
      left: 'left',
      textStyle: {
        color: '#fff',
        fontSize: 12 // 字体大小
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function(params) {
        if (!params?.length) return '无数据';
        // 1. 标题行
        let html = `
        <div style="
          margin-bottom:8px;
          font-weight:bold;
          border-bottom:1px solid #eee;
          padding-bottom:4px;
        ">${params[0].axisValue}年</div>`;

        // 2. 动态处理每个系列
        params.forEach(param => {
          const data = param.data;
          const value = data?.originalValue ?? data?.value;
          const hasValue = value !== undefined && value !== null;

          // 系列名称+值（主行）
          html += `
          <div style="
            display:flex;
            align-items:center;
            margin:4px 0;
            ${!hasValue ? 'opacity:0.6;' : ''}
          ">
            <!-- 颜色圆点 -->
            <span style="
              display:inline-block;
              width:10px;
              height:10px;
              border-radius:50%;
              background:${param.color};
              margin-right:8px;
              flex-shrink:0;
            "></span> 
            <!-- 系列名称 -->
            <span style="
              width:70px;
              color:#666;
              flex-shrink:0;
            ">${param.seriesName} :</span>
            <!-- 数值 -->
            <span style="
              flex:1;
              text-align:right;
              font-family:monospace;
            ">${getRangeName(value)}</span>
          </div>`;
          // ${hasValue ? value : '无数据'}  数据值
          // 区间行（次级信息）
          // if (hasValue) {
          //   html += `
          //   <div style="
          //     display:flex;
          //     margin-left:18px;  /* 与圆点对齐 */
          //     margin-bottom:8px;
          //     color:#888;
          //     font-size:12px;
          //   ">
          //     <span style="width:100px;flex-shrink:0;">价格:</span>
          //     <span>${getRangeName(value)}</span>
          //   </div>`;
          // }
        });

        return html;
      }
    },
    legend: {
      data: ['场景一', '冲为平'],// 后续根据接口返回格式调整为动态
      bottom: 5,
      itemGap: 30 // 图例项之间的间隔
    },
    grid: {
      top: 100,      // 顶部图例占用的高度
      bottom: 60,   // 底部图例占用的高度（增加空间）
      left: 45,
      right: 0
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisTick: {
        show: true, // 显示刻度线
        inside: false // 刻度线朝外
      },
      min: 0, // 设置最小值
      interval: 30, // 设置刻度间隔
      axisLabel: { fontSize: 10,interval: 0,margin: 10,show: true},
      splitLine: {
        show: true,
        lineStyle: {
          color: '#efefef',
          type: 'solid'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 140,
      interval: 20,
      axisLabel: {
        formatter: function(value) {
        // 自定义刻度显示映射
        const map = {
          0: '0',
          20: '0.5',
          40: '1',
          60: '5',
          80: '10',
          100: '50',
          120: '100',
          140: '500'
        };
        return map[value] || '';
        },
        margin: 15,
        fontSize: 12,
        // formatter: '{value}',
        show: true
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: true,
        length: 4,
        lineStyle: {
          color: '#999'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee',
          type: 'solid'
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(250,250,250,0.1)', 'rgba(240,240,240,0.1)']
        }
      }
    },
    series: dynamicSeries
  };
  myChart.setOption(option);
  // 响应式调整
  window.addEventListener('resize', handleResize);
}
function handleResize() {
  myChart?.resize();
}
onMounted(() => {
  handleGetGupiaoList();
  handleGetAnalysisContent();
  handleYearRangeChange();
  // 如果数据为空，强制设置
  if (queryParams.value.dateRange.length === 0) {
    initDatePicker();
  }
});
onBeforeUnmount(() => {
  if (myChart) {
    window.removeEventListener('resize', handleResize);
    myChart.dispose();
    myChart = null;
  }
});
</script>
<style scoped>
.app-container {
  padding: 10px;
}
.chart-container {
  height: 400px;
  min-width: 300px; /* 设置最小宽度防止过度压缩 */
  margin-bottom: 20px;
  width: 100%;
  overflow-x: auto;
  margin-top: 15px;
  overflow: auto; /* 允许水平和垂直滚动 */
  -webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
}
.chart-card{
  margin-top:  20px;
  margin-bottom: 20px;
}
/* h2 {
  color: #1e5799;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
} */
.el-form-item{
  margin-bottom: 0;
}
.el-radio-button {
  margin-right: 10px;
}
.el-radio-button:last-child {
  margin-right: 0;
}
 h1 {
  font-size: 24px;
  color: #333;
 }
.section {
  margin-bottom: 30px;
}
.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  border-left: 4px solid #4a90e2;
  padding-left: 10px;
}

.market-analysis {
  padding: 15px 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.market-analysis p {
  font-weight: bold;
  font-size: 18px;
}
.content-pre {
  white-space: pre-wrap; /* 允许自动换行 */
  word-break: break-word; /* 长单词换行 */
  font-family: inherit; /* 继承正文字体 */
  /* background: #f8f8f8; */
  border-radius: 4px;
  overflow-x: auto; /* 横向滚动 */
  line-height: 22px;
  font-size: 14px;
}
/* 调整选择器样式 */
.van-picker__toolbar {
  padding: 10px;
}

.van-picker-column__item {
  font-size: 14px;
}
/* 在style部分添加 */
.button-group {
  display: flex;
  gap: 8px;
  margin: 16px;
}
.button-group .van-button {
  flex: 1;
  margin-top: 0 !important; /* 覆盖原有样式 */
}
</style>
